package drive.Mapper;

import drive.Model.ChatMessage;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ChatMessageMapper {
    // 查询所有聊天消息
    @Select("SELECT * FROM chatmessage")
    List<ChatMessage> findAll();

    // 根据messageID查询聊天消息
    @Select("SELECT * FROM chatmessage WHERE messageID = #{messageID}")
    ChatMessage findByMessageID(int messageID);

    // 根据chatSessionID查询聊天消息
    @Select("SELECT * FROM chatmessage WHERE chatSessionID = #{chatSessionID}")
    List<ChatMessage> findByChatSessionID(int chatSessionID);

    // 根据senderID查询聊天消息
    @Select("SELECT * FROM chatmessage WHERE senderID = #{senderID}")
    List<ChatMessage> findBySenderID(int senderID);

    // 新增聊天消息
    @Insert("INSERT INTO chatmessage (chatSessionID, senderID, content, sendTime, status) VALUES (#{chatSessionID}, #{senderID}, #{content}, #{sendTime}, #{status})")
    int add(ChatMessage chatMessage);

    // 更新聊天消息
    @Update("UPDATE chatmessage SET chatSessionID = #{chatSessionID}, senderID = #{senderID}, content = #{content}, sendTime = #{sendTime}, status = #{status} WHERE messageID = #{messageID}")
    int update(ChatMessage chatMessage);

    // 删除聊天消息
    @Delete("DELETE FROM chatmessage WHERE messageID = #{messageID}")
    int delete(int messageID);

    /**
     * 根据聊天室ID查找第一条消息
     * @param chatRoomId 聊天室ID
     * @return 第一条消息对象
     */
    @Select("SELECT * FROM chatmessage WHERE chatSessionID = #{chatRoomId} ORDER BY sendTime DESC LIMIT 1")
    ChatMessage findFirstMessageByChatRoomId(int chatRoomId);

    /**
     * 根据聊天室ID分页查询消息
     * @param chatRoomId 聊天室ID
     * @param offset 偏移量
     * @param pageSize 每页大小
     * @return 消息列表
     */
    @Select("SELECT * FROM chatmessage WHERE chatSessionID = #{chatRoomId} ORDER BY sendTime DESC LIMIT #{offset}, #{pageSize}")
    List<ChatMessage> getMessagesByChatRoomId(
            @Param("chatRoomId") int chatRoomId,
            @Param("offset") int offset,
            @Param("pageSize") int pageSize);

    /**
     * 根据聊天室ID统计消息总数
     * @param chatRoomId 聊天室ID
     * @return 消息总数
     */
    @Select("SELECT COUNT(*) FROM chatmessage WHERE chatSessionID = #{chatRoomId}")
    int countMessagesByChatRoomId(@Param("chatRoomId") int chatRoomId);

    /**
     * 更新聊天室中所有消息的状态为已读
     * @param chatRoomId 聊天室ID
     * @param userId 用户ID
     * @return 影响的行数
     */
    @Update("UPDATE chatmessage SET status = 'read' WHERE chatSessionID = #{chatRoomId} AND senderID != #{userId}")
    int updateMessagesStatusAsRead(@Param("chatRoomId") int chatRoomId, @Param("userId") int userId);
}